package com.example.mydemo;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.example.mydemo.utils.CheckPermissionS;
import com.example.mydemo.utils.StorageUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MissedCallReceiver extends BroadcastReceiver {

    Context context;
    public MissedCallReceiver(Context context) {
        this.context = context;
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

            if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                // 获取来电号码
                String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
                if (incomingNumber == null) {
                    return;
                }
                // 查询本地通讯录，获取联系人名称
                String contactName = getContactName(context, incomingNumber);
                if (contactName == null) {
                    contactName = "陌生人";
                }
                // 获取当前时间戳
                long timestampMillis = System.currentTimeMillis();
                Date date = new Date(timestampMillis);
                // 格式化时间戳
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = sdf.format(date);
                // 打印日志，显示来电号码和时间
                Log.d("TAG", "来电信息: " + incomingNumber + " (" + contactName + ")");
                Log.d("TAG", "来电时间: " + formattedDate);
                // 跳转到发送短信给目标手机
                String phoneNumber = StorageUtils.VALUE;//
                String messageData = formatMessageData(formattedDate, incomingNumber, contactName);
                //开启才发送
                if (CheckPermissionS.startObserver) {
                    Log.d("TAG", "发送短信: " + formattedDate);
                    sendSMS(phoneNumber, messageData);
                }
            }
        }
    }
    private String getContactName(Context context, String phoneNumber) {
        ContentResolver cr = context.getContentResolver();
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
        Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
                cursor.close();
                return contactName;
            }
            cursor.close();
        } else {
            return "陌生人";
        }
        return null;
    }

    private String formatMessageData(String time, String sender, String name) {
        if(TextUtils.isEmpty(time) || TextUtils.isEmpty(sender) || TextUtils.isEmpty(name))
        {
            Log.d("TAG", "存在数据为空");
            return "";
        }
        return "时间：" + time + "\n"
                + "类型：" + "电话" + "\n"
                + "姓名：" + name + "\n"
                + "来电人：" + sender + "\n";
    }

    private void sendSMS(String phoneNumber, String message) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS)
                == PackageManager.PERMISSION_GRANTED) {
            if(TextUtils.isEmpty(phoneNumber) || TextUtils.isEmpty(message))
            {
                Log.d("TAG", "手机号码或短信为空");
                return;
            }
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNumber, null, message, null, null);
            Toast.makeText(context, "SMS sent successfully!", Toast.LENGTH_SHORT).show();
            Log.d("TAG", "发送短信给目标手机success");
        } else {
            Toast.makeText(context, "Permission denied to send SMS.", Toast.LENGTH_SHORT).show();
            Log.d("TAG", "无权限发送消息给目标手机");
        }
    }
}
